package cn.vire.electric.simulation.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @auther jw
 * @date 2022-02-21
 */
public class InetAddressUtil {
    private static volatile InetAddress ipHost = null;
    public static InetAddress getInetAddress() {
        if (ipHost != null) {
            return ipHost;
        }
        synchronized (InetAddressUtil.class) {
            if (ipHost == null) {
                Enumeration<NetworkInterface> allNetInterfaces = null;
                try {
                    allNetInterfaces = NetworkInterface.getNetworkInterfaces();
                } catch (SocketException e) {
                    e.printStackTrace();
                }
                while (allNetInterfaces.hasMoreElements()) {
                    NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress _inetAddress = addresses.nextElement();
                        if (_inetAddress != null && _inetAddress instanceof Inet4Address) {
                            ipHost = _inetAddress;
                            return ipHost;
                        }
                    }
                }
            }
            return ipHost = Inet4Address.getLoopbackAddress();
        }
    }

}
